<?php

namespace Beike\Seller\Http\Controllers;

use Beike\Repositories\LanguageRepo;
use Beike\Seller\Http\Requests\CategoryRequest;
use Beike\Seller\Http\Resources\CategoryResource;
use Beike\Seller\Models\SellerCategory;
use Beike\Seller\Repositories\SellerCategoryRepo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = SellerCategoryRepo::list(current_seller_user()->seller_id);
        $data       = [
            'categories' => CategoryResource::collection($categories),
        ];

        return view('seller::pages.categories.index', $data);
    }

    public function create(Request $request)
    {
        $data = [
            'category'     => new SellerCategory(),
            'languages'    => LanguageRepo::all(),
            'descriptions' => null,
        ];

        return view('seller::pages.categories.form', $data);
    }

    public function store(CategoryRequest $request)
    {
        $category = SellerCategoryRepo::create(current_seller_user()->seller_id, $request->all());

        return redirect(seller_route('categories.index'))->with('success', trans('common.created_success'));
    }

    public function edit(Request $request, int $id)
    {
        $category = SellerCategory::query()->find($id);
        if (! $category) {
            throw new \Exception('Category ID is not exists!');
        }
        $descriptions = $category->descriptions->keyBy('locale');

        $data = [
            'category'     => $category,
            'languages'    => LanguageRepo::all(),
            'descriptions' => $descriptions,
        ];

        return view('seller::pages.categories.form', $data);
    }

    public function update(CategoryRequest $request, int $id)
    {
        $category    = SellerCategoryRepo::update(current_seller_user()->seller_id, $id, $request->all());

        return redirect(seller_route('categories.index'))->with('success', trans('common.updated_success'));
    }

    /**
     * 删除分类
     * @param Request  $request
     * @param Category $category
     * @return JsonResponse
     * @throws \Exception
     */
    public function destroy(Request $request, int $id)
    {
        SellerCategoryRepo::delete(current_seller_user()->seller_id, $id);

        return json_success(trans('common.deleted_success'));
    }
}
